package com.exam.project.business.service.impl;

import java.util.Date;
import java.util.List;

import com.exam.common.utils.DateUtils;
import com.exam.common.utils.SecurityUtils;
import com.exam.project.business.domain.*;
import com.exam.project.business.dto.*;
import com.exam.project.business.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.exam.project.business.service.IExamService;

/**
 * 考试表Service业务层处理
 *
 * @author qiuwenbing
 * @date 2025-04-03
 */
@Service
public class ExamServiceImpl implements IExamService {
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private ExamStudentMapper examStudentMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserAnswerMapper userAnswerMapper;
    @Autowired
    private UserExamMapper userExamMapper;

    /**
     * 查询考试表
     *
     * @param id 考试表主键
     * @return 考试表
     */
    @Override
    public Exam selectExamById(Long id) {
        return examMapper.selectExamById(id);
    }

    /**
     * 查询考试表列表
     *
     * @param exam 考试表
     * @return 考试表
     */
    @Override
    public List<Exam> selectExamList(Exam exam) {
        return examMapper.selectExamList(exam);
    }

    /**
     * 新增考试表
     *
     * @param exam 考试表
     * @return 结果
     */
    @Override
    public int insertExam(Exam exam) {
        exam.setCreateTime(DateUtils.getNowDate());
        return examMapper.insertExam(exam);
    }

    /**
     * 修改考试表
     *
     * @param exam 考试表
     * @return 结果
     */
    @Override
    public int updateExam(Exam exam) {
        exam.setUpdateTime(DateUtils.getNowDate());
        return examMapper.updateExam(exam);
    }

    /**
     * 批量删除考试表
     *
     * @param ids 需要删除的考试表主键
     * @return 结果
     */
    @Override
    public int deleteExamByIds(Long[] ids) {
        return examMapper.deleteExamByIds(ids);
    }

    /**
     * 删除考试表信息
     *
     * @param id 考试表主键
     * @return 结果
     */
    @Override
    public int deleteExamById(Long id) {
        return examMapper.deleteExamById(id);
    }

    @Override
    public ExamVo selectMyExamList(Long examId) {
        Long userId = SecurityUtils.getUserId();
        ExamVo vo = new ExamVo();
        // 查询我的考试，
        Exam ex = examMapper.selectExamById(examId);
        vo.setExamId(examId);
        vo.setEndTime(ex.getEndTime());
        vo.setStartTime(ex.getStartTime());
        vo.setExamName(ex.getExamName());
        // 查询题目
        List<QuestionVo> questionVos = questionMapper.selectQuestionByExamId(examId);
        if (!questionVos.isEmpty()) {
            questionVos.forEach(item -> {
                //  如果已经答题了，需要查询答题结果
                UserAnswer ua = new UserAnswer();
                ua.setQuestionId(item.getQuestionId());
                ua.setExamId(examId);
                ua.setUserId(userId);
                List<UserAnswer> us = userAnswerMapper.selectUserAnswerList(ua);
                if (!us.isEmpty() && us.size() > 0) {
                    item.setAnswer(us.get(0).getStudentAnswerContent());
                    item.setScore(us.get(0).getScore());
                    item.setIsCorrect(us.get(0).getIsCorrect());
                }
                // 查看选项
                List<ChoiceOption> choiceOptions = questionMapper.selectMyOptions(item.getQuestionId());
                if (!choiceOptions.isEmpty()) {
                    item.setOptions(choiceOptions);
                }
            });
        }
        vo.setQuestionVos(questionVos);
        return vo;
    }

    @Override
    public ExamVo selectExamInfo(Long examId, Long userId) {
        ExamVo vo = new ExamVo();
        // 查询我的考试，
        Exam ex = examMapper.selectExamById(examId);
        vo.setExamId(examId);
        vo.setEndTime(ex.getEndTime());
        vo.setStartTime(ex.getStartTime());
        vo.setExamName(ex.getExamName());
        // 查询题目
        List<QuestionVo> questionVos = questionMapper.selectQuestionByExamId(examId);
        if (!questionVos.isEmpty()) {
            questionVos.forEach(item -> {
                //  如果已经答题了，需要查询答题结果
                UserAnswer ua = new UserAnswer();
                ua.setQuestionId(item.getQuestionId());
                ua.setExamId(examId);
                ua.setUserId(userId);
                List<UserAnswer> us = userAnswerMapper.selectUserAnswerList(ua);
                if (!us.isEmpty() && us.size() > 0) {
                    item.setAnswer(us.get(0).getStudentAnswerContent());
                    item.setScore(us.get(0).getScore());
                    item.setIsCorrect(us.get(0).getIsCorrect());
                }
                // 查看选项
                List<ChoiceOption> choiceOptions = questionMapper.selectMyOptions(item.getQuestionId());
                if (!choiceOptions.isEmpty()) {
                    item.setOptions(choiceOptions);
                }
            });
        }
        vo.setQuestionVos(questionVos);
        return vo;
    }

    @Override
    public Exam myExam() {
        Exam exam = examMapper.selectMyExam(SecurityUtils.getUserId());
        if (exam != null) {
            UserExam userExam = new UserExam();
            userExam.setExamId(exam.getId());
            userExam.setUserId(SecurityUtils.getUserId());
            List<UserExamDto> userExams = userExamMapper.selectUserExamList(userExam);
            if (!userExams.isEmpty()) {
                exam.setSubmit(true);
            }
        }
        return exam;
    }


    @Override
    public List<UserDto> queryChoose(Long examId) {
        return examMapper.queryChoose(examId);
    }

    @Override
    public int queryIsChoose(Long userId, Long examId) {
        ExamStudent es = new ExamStudent();
        es.setExamId(examId);
        es.setUserId(userId);
        List<ExamStudent> examStudents = examStudentMapper.selectExamStudentList(es);
        if (examStudents.isEmpty() && examStudents.size() > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public void submitExam(ExamAnswerDto dto) {
        userAnswerMapper.deleteUserAnswerByExamUserId(dto.getExamId(), SecurityUtils.getUserId());
        Long score = 0L;
        for (int i = 0; i < dto.getAnswers().size(); i++) {
            UserAnswer item = dto.getAnswers().get(i);
            UserAnswer ua = new UserAnswer();
            ua.setExamId(dto.getExamId());
            ua.setUserId(SecurityUtils.getUserId());
            ua.setQuestionId(item.getQuestionId());
            ua.setStudentAnswerContent(item.getStudentAnswerContent());
            Question question = questionMapper.selectQuestionById(item.getQuestionId());
            Integer isCorrect = null;
            if ("coding".equals(question.getQuestionType())) {
                //不判断正确

            } else {
                if (question.getCorrectAnswer().equals(item.getStudentAnswerContent())) {
                    isCorrect = 1;
                    ua.setScore(question.getScore());
                    score = score + question.getScore();
                } else {
                    isCorrect = 0;
                    ua.setScore(0L);
                }
            }
            ua.setIsCorrect(isCorrect);
            userAnswerMapper.insertUserAnswer(ua);
        }
        UserExam ue = new UserExam();
        ue.setExamId(dto.getExamId());
        ue.setUserId(SecurityUtils.getUserId());
        ue.setStartTime(dto.getStartTime());
        ue.setEndTime(new Date());
        ue.setScore(score);
        userExamMapper.insertUserExam(ue);
    }

    @Override
    public void submitExamScore(SubmitScoreDto dto) {
        UserExam ue = new UserExam();
        ue.setExamId(dto.getExamId());
        ue.setUserId(dto.getUserId());
        List<UserExamDto> userExamDtos = userExamMapper.selectUserExamList(ue);

        Long score = 0L;
        for (int i = 0; i < dto.getUserAnswerList().size(); i++) {
            UserAnswer query = new UserAnswer();
            UserAnswer item= dto.getUserAnswerList().get(i);
            query.setQuestionId(item.getQuestionId());
            query.setUserId(dto.getUserId());
            query.setExamId(dto.getExamId());

            UserAnswer ua = userAnswerMapper.selectUserAnswer(query);
            if (ua != null) {
                UserAnswer update = new UserAnswer();
                update.setId(ua.getId());
                update.setScore(item.getScore());
                score+=item.getScore();
                userAnswerMapper.updateUserAnswer(update);
            }

        }
        if (!userExamDtos.isEmpty() && userExamDtos.size()>0 ) {
            UserExamDto userExamDto = userExamDtos.get(0);
            UserExam update = new UserExam();
            update.setId(userExamDto.getId());
            update.setIsConfirmed(1);
            update.setScore(score);
            userExamMapper.updateUserExam(update);
        }
    }
}
